#include "ipc_common.hpp"
#include <iostream>
#include <string>
#include <filesystem>
#include <sstream>

// 检查客户端进程是否为同目录下的client.exe
bool IsValidClient(HANDLE pipe) {
    // 获取客户端进程ID
    ULONG clientPid = 0;
    if (!GetNamedPipeClientProcessId(pipe, &clientPid)) {
        std::cerr << "获取客户端进程ID失败. 错误码: " << GetLastError() << std::endl;
        return false;
    }
    
    // 打开客户端进程
    HANDLE clientProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, clientPid);
    if (clientProcess == NULL) {
        std::cerr << "打开客户端进程失败. 错误码: " << GetLastError() << std::endl;
        return false;
    }
    
    // 获取客户端进程路径
    char clientPath[MAX_PATH];
    DWORD pathSize = MAX_PATH;
    if (!QueryFullProcessImageNameA(clientProcess, 0, clientPath, &pathSize)) {
        std::cerr << "获取客户端进程路径失败. 错误码: " << GetLastError() << std::endl;
        CloseHandle(clientProcess);
        return false;
    }
    
    // 获取服务端进程路径
    char serverPath[MAX_PATH];
    pathSize = MAX_PATH;
    if (!GetModuleFileNameA(NULL, serverPath, pathSize)) {
        std::cerr << "获取服务端进程路径失败. 错误码: " << GetLastError() << std::endl;
        CloseHandle(clientProcess);
        return false;
    }
    
    // 使用std::filesystem比较路径
    std::filesystem::path clientFilePath(clientPath);
    std::filesystem::path serverFilePath(serverPath);
    std::filesystem::path expectedClientPath = serverFilePath.parent_path() / "ipc_client.exe";
    
    // 关闭进程句柄
    CloseHandle(clientProcess);
    
    // 检查客户端是否为同目录下的client.exe
    bool isValid = (clientFilePath == expectedClientPath);
    
    if (!isValid) {
        std::cerr << "非法客户端连接尝试: " << clientFilePath.string() << std::endl;
        std::cerr << "期望的客户端路径: " << expectedClientPath.string() << std::endl;
    }
    
    return isValid;
}

int main() {
    std::cout << "启动IPC服务端...\n";

    // 创建命名管道
    HANDLE pipe = CreateNamedPipeA(
        PIPE_NAME,
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
        1,
        sizeof(Message),
        sizeof(Message),
        0,
        nullptr
    );

    if (pipe == INVALID_HANDLE_VALUE) {
        std::cerr << "创建管道失败. 错误码: " << GetLastError() << std::endl;
        return 1;
    }

    while (true) {
        std::cout << "等待客户端连接...\n";

        // 等待客户端连接
        if (!ConnectNamedPipe(pipe, nullptr)) {
            std::cerr << "连接失败. 错误码: " << GetLastError() << std::endl;
            CloseHandle(pipe);
            return 1;
        }

        // 验证客户端进程
        if (!IsValidClient(pipe)) {
            std::cout << "拒绝非法客户端连接\n";
            DisconnectNamedPipe(pipe);
            continue;  // 继续等待下一个连接
        }

        std::cout << "合法客户端已连接\n";

        // 主循环
        while (true) {
            // 读取客户端消息
            std::string message = ReadMessage(pipe);
            if (message.empty()) {
                std::cout << "客户端断开连接\n";
                break;
            }

            std::cout << "收到: " << message << std::endl;

            // 发送响应
            std::string response = "服务器收到消息: " + message;
            if (!WriteMessage(pipe, response)) {
                std::cerr << "发送响应失败\n";
                break;
            }
        }

        // 断开连接，准备接受下一个客户端
        DisconnectNamedPipe(pipe);
    }

    // 清理
    CloseHandle(pipe);
    return 0;
}
